package core
{
	import utils.T;
	import vo.GeneralVO;
	
	/**
	 * 游戏中的部分计算公式及算法
	 * @author WLDragon 2014-04-02
	 */
	public class Algorithm
	{
		/**
		 * 寻找金米宝人才
		 * @param	gid  执行任务的武将ID
		 * @param   type 指定寻找的是哪一种类型
		 */
		static public function find(gid:int,type:String = ""):String
		{
			var val:String = type;
			var xml:XML = T.db.getXml(Cnt.XML_ALGORITHM).find[0];
			if (type == "")
			{
				var g:GeneralVO = T.db.getRecord(Cnt.VO_GENERAL, gid);
				var k:int = g.knowledge;
				var m:int = g.morality;
				
				var r:Number = Math.random();
				var items:XMLList = xml.cm.(@minMor <= m && m <= @maxMor)[0].ck.(@minKno <= k && k <= @maxKno)[0].item;
				for each(var x:XML in items)
				{
					if (r < Number(x.@r))
					{
						val = x.@val;
						break;
					}
				}
			}
			
			var s:String;
			var w:int;
			
			//1-金30~70 2-米50~90 3-金80~120 4-宝1~3
			//5-找人(不要钱) 6-找人(要钱) 7-失败
			if (val == "1")
			{
				w = 30 + Math.random() * 40;
				s = val + "|" + String((xml.type.(@id == val)[0]).@text).replace("%%", w);
				Gbl.activeCastle.gold += w;
			}
			else if (val == "2")
			{
				w = 50 + Math.random() * 40;
				s = val + "|" + String((xml.type.(@id == val)[0]).@text).replace("%%", w);
				Gbl.activeCastle.rice += w;
			}
			else if (val == "3")
			{
				w = 80 + Math.random() * 40;
				s = val + "|" + String((xml.type.(@id == val)[0]).@text).replace("%%", w);
				Gbl.activeCastle.gold += w;
			}
			else if (val == "4")
			{
				w = 1 + Math.random() * 3;
				s = val + "|" + String((xml.type.(@id == val)[0]).@text).replace("%%", w);
				Gbl.activeCastle.treasure += w;
			}
			else
			{
				s = val + "|" + (xml.type.(@id == val)[0]).@text;
			}
			
			return s;
		}
		
		/**
		 * 查看有没有在野武将
		 * @return
		 */
		static public function findGeneral():GeneralVO
		{
			if (Gbl.activeCastle.storeList.length > 0)
			{
				var id:int = Gbl.activeCastle.storeList[0];
				var g:GeneralVO = T.db.getRecord(Cnt.VO_GENERAL, id);
				if (g.born <= Gbl.sys.year)
					return g;
			}
			
			return null;
		}
	}

}